<template>
	<om-addpage :menuName="menuName" :busCode="busCode" @formSubmit='formSubmit'>
		<view v-show="false">
			<input v-model="formdata.zposId" name="zposId" />
			<input v-model="formdata.userIds" name="userIds" />
			<input v-model="formdata.classesId" name="classesId" />
			<input v-model="formdata.classesName" name="classesName" />
			<input v-model="formdata.workHoursCode" name="workHoursCode" />
			
			<input v-model="formdata.workHoursName" name="workHoursName" />
			<input v-model="formdata.salaryHandleId" name="salaryHandleId" />
			<input v-model="formdata.salaryHandleName" name="salaryHandleName" />
			<input v-model="formdata.ratio" name="ratio" />
			<input v-model="formdata.costInstId" name="costInstId" />
			<input v-model="formdata.costInstName" name="costInstName" />
		</view>
		<uni-list title="加班信息">
			<uni-list-item :showArrow="true">
				<view class="tui-flex">
					<view class="tui-col-5"><om-label label="制表岗位"></om-label></view>
					<view class="tui-right tui-col-7">
						<picker mode="selector" name="zposIndex" @change="zposFunc" :range="zposList" :value="zposIndex" range-key="posname">
							<view>{{ zposList.length ? zposList[zposIndex].posname : '请选择' }}</view>
						</picker>
					</view>
				</view>
			</uni-list-item>
			<uni-list-item  :showArrow="true">
				<view class="tui-flex">
					<view class="tui-col-5"><om-label label="加班日期" required></om-label></view>
					<view class="tui-right  tui-col-7">
						<picker mode="date" @change="bindDateChange" name="overTimeDay" v-model="formdata.overTimeDay" :value="formdata.overTimeDay">
							<view>{{formdata.overTimeDay.trim()?formdata.overTimeDay:"请选择"}}</view>
						</picker>
					</view>
				</view>
			</uni-list-item>
			<uni-list-item  @click="showUser" :showArrow="true">
				<view class="tui-flex">
					<view class="tui-col-5"><om-label label="加班人员" required></om-label></view>
					<view class="tui-right tui-col-7">
						{{userNames || '请选择'}}
					</view>
				</view>
			</uni-list-item>
			<uni-list-item  :showArrow="true" :showClear="~classesIndex ? true : false" @iconClear="classClearFunc">
				<view class="tui-flex">
					<view class="tui-col-5"><om-label label="班次"></om-label></view>
					<view class="tui-right tui-col-7">
						<picker mode="selector" name="classesIndex" @change="classesFunc" :range="classesList" :value="classesIndex" range-key="classesName">
							<view>{{ ~classesIndex ? classesList[classesIndex].classesName : '请选择' }}</view>
						</picker>
					</view>
				</view>
			</uni-list-item>
			<uni-list-item  :showArrow="true">
				<view class="tui-flex">
					<view class="tui-col-5"><om-label label="开始时间" required></om-label></view>
					<view class="tui-right tui-col-7">
						<picker mode="time" @change="startTimeFunc" v-model="formdata.startTime" name="startTime" :value="formdata.startTime">
							<view>{{formdata.startTime.trim()?formdata.startTime:"请选择"}}</view>
						</picker>
					</view>
				</view>
			</uni-list-item>
			<uni-list-item  :showArrow="true">
				<view class="tui-flex">
					<view class="tui-col-5"><om-label label="结束时间" required></om-label></view>
					<view class="tui-right tui-col-7">
						<picker mode="time" @change="endTimeFunc" v-model="formdata.endTime" name="endTime" :value="formdata.endTime">
							<view>{{formdata.endTime.trim()?formdata.endTime:"请选择"}}</view>
						</picker>
					</view>
				</view>
			</uni-list-item>
			<uni-list-item  :showArrow="false">
				<view class="tui-flex">
					<view class="tui-col-5"><om-label label="加班工时"></om-label></view>
					<view class="tui-right tui-col-7">{{formdata.workHoursName}}</view>
				</view>
			</uni-list-item>
			<uni-list-item  :showArrow="!formdata.overTimeTypeName">
				<view class="tui-flex">
					<view class="tui-col-5"><om-label label="计酬处理方式" :required="!formdata.overTimeTypeName"></om-label></view>
					<view v-if="formdata.overTimeTypeName" class="tui-right tui-col-7">
						{{formdata.overTimeTypeName}}
					</view>
					<view v-else class="tui-right tui-col-7">
						<picker
							mode="selector"
							name="salaryHandleIndex"
							@change="salaryHandleFunc"
							:range="salaryHandleList"
							:value="salaryHandleIndex"
							range-key="dicname"
						>
							<view>{{ formdata.salaryHandleName ? formdata.salaryHandleName : '请选择' }}</view>
						</picker>
					</view>
				</view>
			</uni-list-item>
			<uni-list-item  :showArrow="true">
				<view class="tui-flex">
					<view class="tui-col-5"><om-label label="费用承担机构" required></om-label></view>
					<view class="tui-right tui-col-7" @click="costInstFunc">
						{{formdata.costInstName || '请选择'}}
					</view>
				</view>
			</uni-list-item>
			<uni-list-item  :showArrow="false">
				<view class="tui-flex">
					<view class="tui-col-5"><om-label label="外出加班不考勤"></om-label></view>
					<view class="tui-right tui-col-7">
						<switch @change="switchOutNoAttence" :class="formdata.isoutNoAttence?'checked':''" v-model="formdata.isoutNoAttence" :checked="formdata.isoutNoAttence?true:false" name='isoutNoAttence'></switch>
					</view>
				</view>
			</uni-list-item>
			<uni-list-item  :showArrow="false">
				<view class="tui-flex">
					<view class="tui-col-5"><om-label label="加班事由" required></om-label></view>
					<view class="tui-left tui-col-7"><textarea :auto-height="true" class="om-textarea" v-model="formdata.instructions" name="instructions" placeholder="请输入..." /></view>
				</view>
			</uni-list-item>
		</uni-list>
	</om-addpage>
</template>

<script>
	const form = require("../../../static/js/formValidation.js")
import dateTimePicker from '@/static/js/dateTimePicker.js';
import {loadZpos} from '@/static/js/formOld.js';
import { getUrl, ignoreHtml, confirmModal,errorModal} from '@/static/js/common.js';
export default {
	provide() {
		return {
			formPage: this
		};
	},
	data() {
		return {
			formdata:{
				zposId:'',
				overTimeDay:dateTimePicker.getNewDate(),
				userIds:'',
				classesId:'',
				classesName:'',
				startTime:'',
				endTime:'',
				workHoursCode:'',
				workHoursName:'',
				salaryHandleId:'',
				salaryHandleName:'',
				overTimeTypeId:"",
				overTimeTypeName:"",
				overTimeTypeRatio:"",
				salaryPosId:"",
				ratio:'',
				costInstId:'',
				costInstName:'',
				isoutNoAttence:false,
				instructions:"",
				
			},
			userNames:'',
			zposIndex: 0,
			zposList: [],
			classesIndex: -1,
			classesList: [],
			salaryHandleIndex: 0,
			salaryHandleList: [],
			selectUsers:[],
			menuName: '',
			id: '',
			busCode: '',
			userCacheKey:"hr-kq-overtime-user-cache",
			instCacheKey:"hr-kq-overtime-inst-cache"
		};
	},
	watch:{
		selectUsers: function(newValue, oldValue) {
			if (newValue && newValue.length) {
				this.formdata.userIds = newValue.map(e=>e.id).join(",")
				this.userNames = newValue.map(e=>e.username).join(",")
			}else{
				this.formdata.userIds = ""
				this.userNames =""
			}
			this.userConfirm()
		},
	},
	methods: {
		switchOutNoAttence(e){
			this.formdata.isoutNoAttence = e.detail.value
		},
		salaryHandleFunc(e) {
			this.salaryHandleIndex = e.target.value;
			this.setSalaryHandle()
		},
		setSalaryHandle(){
			this.formdata.salaryHandleId = this.salaryHandleList[this.salaryHandleIndex].id;
			this.formdata.salaryHandleName = this.salaryHandleList[this.salaryHandleIndex].dicname;
			this.formdata.ratio = this.salaryHandleList[this.salaryHandleIndex].ratio;
		},
		//班次
		classesFunc(e) {
			let _that = this;
			_that.classesIndex = e.target.value;
			_that.formdata.classesId = this.classesList[_that.classesIndex].classesId;
			_that.formdata.classesName = this.classesList[_that.classesIndex].classesName;
			_that.om
				.request('ttimeTable/getTime', {
					classesId: _that.formdata.classesId
				})
				.then(res => {
					if (res.succeed) {
						_that.formdata.startTime = res.value.startTime;
						_that.formdata.endTime = res.value.endTime;
						//计算加班工时
						_that.workHoursFunc(res.value.ratedTime);
						//验证时间是否重叠
						_that.verifyTimeFunc();
					}
				});
		},
		classClearFunc() {
			this.classesIndex = -1;
			this.formdata.startTime = '';
			this.formdata.endTime = '';
			this.formdata.workHoursCode = '';
			this.formdata.workHoursName = '';
			this.formdata.classesId = '';
			this.formdata.classesName = '';
		},
		/**
		 * 制表岗位
		 */
		zposFunc(e) {
			let _that = this
			_that.zposIndex = e.detail.value
			_that.formdata.zposId = this.zposList[e.detail.value].id
			_that.formdata.costInstId = this.zposList[e.detail.value].instId
			_that.formdata.costInstName = this.zposList[e.detail.value].instName
			//加载姓名
			// _that.loadUserNameFunc();
		},

		showUser() {
			if(!this.formdata.zposId){
				this.om.toast("请选择制表岗位")
				return
			}
			uni.setStorage({
				key:this.userCacheKey,
				data:this.selectUsers
			})
			var url = getUrl("../../public/multiSearch/multiSearch",{
				other:JSON.stringify({
					zposId:this.formdata.zposId
				}),
				valuefield:"id",
				namefield:"username",
				searchfield:"q",
				initload:true,
				url:"orgInstPosUserOfficial/findAllChildrenNotIntime",
				cachename:this.userCacheKey,
				placeholder:"请输入姓名",
				pagination:true
			})
			uni.navigateTo({
				url:url
			})
		},
		userConfirm() {
			let _that = this
			if(this.selectUsers.length == 1){
				var user = this.selectUsers[0]
				this.om.request("tposition/getPosInfo",{"posId": user.salaryPosId}).then(res=>{
					_that.formdata.salaryPosId = user.salaryPosId
					_that.formdata.overTimeTypeId = res.value.overTimeTypeId
					_that.formdata.overTimeTypeName = res.value.overTimeTypeName
					_that.formdata.overTimeTypeRatio = res.value.overTimeTypeRatio
					_that.formdata.salaryHandleId = res.value.overTimeTypeId
					_that.formdata.salaryHandleName = res.value.overTimeTypeName
					_that.formdata.ratio = res.value.overTimeTypeRatio
				})
			}else{
				_that.formdata.salaryPosId = ""
				_that.formdata.overTimeTypeId = ""
				_that.formdata.overTimeTypeName = ""
				_that.formdata.overTimeTypeRatio = ""
			}
		},
		/**
		 * 加班日期
		 */
		bindDateChange(e) {
			this.formdata.overTimeDay = e.detail.value;
			this.verifyDateFunc();
		},
		/**
		 * 选择日期验证
		 */
		verifyDateFunc() {
			let _that = this;
			_that.om.request('wxOverTime/verifyDate', {
					date: _that.formdata.overTimeDay
				})
				.then(res => {
					if (res.succeed) {
						_that.verifyTimeFunc();
					} else {
						_that.formdata.overTimeDay = '';
						_that.om.toast(ignoreHtml(res.msg), 3000);
					}
				});
		},
		//验证时间是否重叠
		verifyTimeFunc() {
			let _that = this;
			if (!_that.formdata.startTime || !_that.formdata.endTime || !_that.formdata.overTimeDay) {
				return;
			}
			let userId = null;
			if (_that.selectUserList && _that.selectUserList.length === 1) {
				userId = _that.selectUserList[0].id;
			}
			_that.om
				.request('wxOverTime/verifyConflictTime', {
					startTime: _that.formdata.startTime,
					endTime: _that.formdata.endTime == '00:00' ? '24:00' : _that.formdata.endTime,
					date: _that.formdata.overTimeDay,
					userId: userId
				})
				.then(res => {
					if (res.value) {
						errorModal(
							_that,
							'提示信息',
							ignoreHtml(res.value),
							function() {
								_that.formdata.startTime = '';
								_that.formdata.endTime = '';
								_that.formdata.workHoursCode = '';
								_that.formdata.workHoursName = '';
							}
						)
					} else {
						_that.verifySingleTime();
					}
				})
		},

		//验证单次时长
		verifySingleTime() {
			let _that = this;
			if (_that.x2 && !~_that.classesIndex) {
				let whc = _that.formdata.workHoursCode.replace(':', '.');
				if (whc > _that.x2) {
					confirmModal(
						_that,
						'提示信息',
						'加班没有选择班次，单条加班时长超过了' + _that.x2 + '小时，加班时段可能包含休息时段，是否继续？',
						function() {},
						function() {
							_that.formdata.endTime = '';
							_that.formdata.workHoursCode = '';
							_that.formdata.workHoursName = '';
						}
					);
				}
			}
		},
		//开始时间
		startTimeFunc(e) {
			let _that = this;
			let startTime = _that.timeFunc(e.target.value);
			_that.formdata.startTime = startTime;
			_that.classesIndex = -1;
			if (_that.formdata.endTime) {
				if (_that.formdata.startTime > _that.formdata.endTime && _that.formdata.endTime != '00:00') {
					_that.formdata.endTime = '';
					_that.formdata.workHoursCode = '';
					_that.formdata.workHoursName = '';
				} else {
					//计算加班工时
					_that.workHoursFunc();
					//验证时间是否重叠
					_that.verifyTimeFunc();
				}
			}
		},

		//四舍五入时间
		timeFunc(q) {
			if (this.x1 > 0) {
				let qs = q.split(':');
				if (qs[0].length == 1) {
					qs[0] = '0' + qs[0];
				}
				if (qs[1].length > 0) {
					qs[1] = Math.round(qs[1] / 10) * 10;
					if (qs[1] == 60) {
						qs[1] = '00';
						qs[0] = qs[0] * 1 + 1;
						if (qs[0] == 24) {
							qs[0] = '00';
						}
					}
				}
				return qs[0] + ':' + qs[1];
			} else {
				return q;
			}
		},

		//结束时间
		endTimeFunc(e) {
			let _that = this;
			let endTime = _that.timeFunc(e.target.value);
			_that.formdata.endTime = endTime;
			_that.classesIndex = -1;
			if (_that.formdata.startTime) {
				if (_that.formdata.startTime > _that.formdata.endTime && _that.formdata.endTime != '00:00') {
					_that.formdata.startTime = '';
					_that.formdata.workHoursCode = '';
					_that.formdata.workHoursName = '';
				} else {
					//计算加班工时
					_that.workHoursFunc();
					//验证时间是否重叠
					_that.verifyTimeFunc();
				}
			}
		},

		/**
		 * 计算加班工时
		 */
		workHoursFunc(q) {
			let _that = this;
			if (!q) {
				let st = _that.formdata.startTime.replace(':', '.');
				let et = _that.formdata.endTime.replace(':', '.');
				if (_that.formdata.endTime == '00:00') {
					et = '24.00';
				}
				if (et.substring(3, 5) < st.substring(3, 5)) {
					et -= 0.4;
				}
				q = (et - st).toFixed(2) + '';
			} else {
			  let q1 = q.split('.');
			  q = q1[0] + '.' + parseInt(q1[1]) * 6;
			}
			q = q.replace('.', ':');
			let qs = q.split(':');
			if (qs[0] && qs[0].length == 1) {
				qs[0] = '0' + qs[0];
			}
			if (qs[1] && qs[1].length == 1) {
				qs[1] = qs[1] + '0';
			}
			q = qs[0] + ':' + qs[1];
			let workHoursName = parseInt(qs[0]) + '小时' + parseInt(qs[1]) + '分钟';
			if (qs[0] == '00') {
				workHoursName = parseInt(qs[1]) + '分钟';
			}
			if (qs[1] == '00') {
				workHoursName = parseInt(qs[0]) + '小时';
			}
			if (qs[0] == '00' && qs[1] == '00') {
				workHoursName = '0';
			}
			_that.formdata.workHoursCode = q;
			_that.formdata.workHoursName = workHoursName;
		},
		/**
		 * 费用承担机构
		 */
		costInstFunc(e) {
			var url = getUrl("../../public/search/search",{
				namefield:"instname",
				searchfield:"instName",
				initload:true,
				url:"tinstitution/findNotBoard1",
				cachename:this.instCacheKey,
				placeholder:"请输入机构名称",
				method:"post"
			})
			uni.navigateTo({
				url:url
			})
		},
		formSubmit: function(formdata) {
			//表单规则
			let rules = [{
				name: "zposId",
				rule: ["required"], 
				msg: ["请选择制表岗位"]
			}, {
				name: "overTimeDay",
				rule: ["required"],
				msg: ["请选择加班日期"]
			}, {
				name: "startTime",
				rule: ["required"],
				msg: ["请选择加班开始时间"]
			}, {
				name: "endTime",
				rule: ["required"],
				msg: ["请选择加班结束时间"]
			}, {
				name: "salaryHandleId",
				rule: ["required"],
				msg: ["请选择计酬处理方式"]
			}, {
				name: "costInstId",
				rule: ["required"],
				msg: ["请选择费用承担机构"]
			}, {
				name: "instructions",
				rule: ["required"],
				msg: ["请输入加班事由"]
			}];
			let _that = this;
			if(!formdata || Object.keys(formdata).length==0){
				formdata = _that.formdata
			}
			let checkRes = form.validation(formdata, rules);
			if (!checkRes) {
				_that.om.formSave('wxOverTime/save',  {
					zposId:formdata.zposId,
					overTimeDay:formdata.overTimeDay,
					userIds:formdata.userIds,
					objStr:JSON.stringify(formdata)
				}, _that)
			} else {
				_that.om.toast(checkRes);
			}
			
		},
		initLoad() {
			let _that = this;
			loadZpos(_that,null,'您没有加班表单的制表权限，暂不能做表')
			//加载班次
			_that.om.request('ttimeTable/getClassesList').then(res => {
				_that.classesList = res;
			});

			//加载计酬处理方式
			_that.om.request('askLeaveDict/getOverTimeList').then(res => {
				_that.salaryHandleList = res;
				_that.setSalaryHandle()
			});
		}
	},

	onLoad: function(options) {
		let _that = this;
		_that.menuName = options.title || '加班'
		uni.setNavigationBarTitle({
			title: _that.menuName
		});
		_that.busCode = options.code;
		_that.om.request('wxOverTime/getConst').then(res => {
			if (res.succeed) {
				_that.busCode = res.value.busCode || 'HRS1204';
				_that.x1 = res.value.x1;
				_that.x2 = res.value.x2;
				_that.initLoad();
			}
		});
	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function() {
		let _that = this;
		uni.getStorage({
			key: this.instCacheKey,
			success: function(res) {
				
				_that.formdata.costInstName = res.data.instname
				_that.formdata.costInstId = res.data.id
				uni.removeStorage({
					key: this.instCacheKey
				});
			}
		});
		uni.getStorage({
			key: _that.userCacheKey,
			success: function(res) {
				_that.selectUsers = res.data;
				uni.removeStorage({
					key: _that.userCacheKey
				});
			}
		});
	}
};
</script>

<style>
	
</style>
